﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ESRI.ArcGIS.Carto;
using CommonLib;
using ESRI.ArcGIS.Geodatabase;
using System.Threading;

namespace FormLib
{
    public partial class DJUpdate : DevExpress.XtraEditors.XtraForm
    {
        private IFeatureLayer m_featureLayer = null;
        private System.Threading.Thread updateThread;
        private bool isRunning = false;
        public DJUpdate(string updateContent, IFeatureLayer featureLayer)
        {
            InitializeComponent();
            m_featureLayer = featureLayer;
            this.Text = updateContent;
            //初始化期数平均每期变动率
            switch (updateContent)
            {
                case "市区商业基准地价更新":
                case "市区住宅基准地价更新":
                    this.txtQSBDL.Text = "0.0037";
                    break;
                case "市区工业基准地价更新":
                    this.txtQSBDL.Text = "0.0015";
                    break;
            }
        }

        private void DJUpdate_Load(object sender, EventArgs e)
        {
            this.DEStart.EditValue = DateTime.Now.ToString();
            this.DEEnd.EditValue = DateTime.Now.AddMonths(1).ToString();

        }

        private void sBtnEdit_Click(object sender, EventArgs e)
        {
            if (this.sBtnEdit.Text == "保存")
            {
                this.sBtnEdit.Text = "修改";
                this.txtQSBDL.Properties.ReadOnly = true;
            }
            else
            {
                this.sBtnEdit.Text = "保存";
                this.txtQSBDL.Properties.ReadOnly = false;
            }
        }

        private void sBtnUpdate_Click(object sender, EventArgs e)
        {
            if (sBtnUpdate.Text == "完成")
            {
                this.Close();
            }
            else
            {
                if (!this.txtQSBDL.Properties.ReadOnly)
                {
                    MessageBox.Show("请先保存期数平均每期变动率。");
                    return;
                }
                else if (Convert.ToDateTime(this.DEEnd.Text) < Convert.ToDateTime(this.DEStart.Text))
                {
                    MessageBox.Show("请输入正确的期数起始时间。");
                    return;
                }
                else if (m_featureLayer == null)
                {
                    MessageBox.Show("请选择正确的基准地价数据。");
                    return;
                }
                updateThread = new System.Threading.Thread(updateDJ);
                updateThread.Start();
            }
        }
        void updateDJ()
        {
            this.BeginInvoke(new MethodInvoker(() =>
            {
                try
                {
                    this.sBtnUpdate.Text = "更新中…";
                    this.sBtnUpdate.Enabled = false;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }));
            IDataset pDataset = (IDataset)m_featureLayer.FeatureClass;
            if (null == pDataset)
            {
                this.BeginInvoke(new MethodInvoker(() =>
                {
                    try
                    {
                        MessageBox.Show("请选择正确的基准地价数据。");
                        this.sBtnUpdate.Enabled = true;
                        this.sBtnUpdate.Text = "更新";
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }));
                return;
            }
            isRunning = true;
            IWorkspaceEdit pWorkspaceEdit = (IWorkspaceEdit)pDataset.Workspace;
            try
            {
                int mouths = 0;
                string qsdl = "";
                this.BeginInvoke(new MethodInvoker(() =>
                {
                    try
                    {
                        qsdl = this.txtQSBDL.Text;
                        mouths = CommonTools.GetMonth(this.DEStart.Text, this.DEEnd.Text);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }));
                #region 开始编辑
                if (!pWorkspaceEdit.IsBeingEdited())
                {
                    pWorkspaceEdit.StartEditing(true);
                }
                pWorkspaceEdit.StartEditOperation();
                #endregion
                #region 编辑
                //开始更新
                string updateField = "基准地价";
                IFeatureCursor pFeatureCursor = m_featureLayer.FeatureClass.Update(null, false);
                IFeature pFeature = pFeatureCursor.NextFeature();
                if (pFeature != null)
                {
                    if (pFeature.Fields.FindField("XJZDJ") == -1 || pFeature.Fields.FindField("XJZDJ") == -1)
                    {
                        this.BeginInvoke(new MethodInvoker(() =>
                        {
                            try
                            {
                                MessageBox.Show("请先对数据进行处理！");
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }));
                        return;
                    }
                    //确定更新的字段
                    if (!string.IsNullOrEmpty(pFeature.get_Value(pFeature.Fields.FindField("XJZDJ")).ToString ()))
                    {
                        updateField = "XJZDJ";
                    }
                }
                #region 进度条

                int maxValue = m_featureLayer.FeatureClass.FeatureCount(null);
                this.BeginInvoke(new MethodInvoker(() =>
                {
                    try
                    {
                        ///初始化设置进度条
                        progressBarControl.Visible = true;
                        progressBarControl.Reset();
                        progressBarControl.EditValue = 0;
                        progressBarControl.Properties.Minimum = 0;
                        progressBarControl.Properties.Maximum = maxValue; //可改   值越大,效果越好  
                        progressBarControl.Properties.Step = 1; //步进值  
                        Application.DoEvents();//加上此句,防止卡住 
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }));
                #endregion
                DateTime updateTime = DateTime.Now;
                while (pFeature != null)
                {
                    //基准地价
                    this.BeginInvoke(new MethodInvoker(() =>
                    {
                        try
                        {
                            progressBarControl.PerformStep();//执行  
                            Application.DoEvents();
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }));
                    double jzdj=-1;
                    if(!double.TryParse(pFeature.get_Value(pFeature.Fields.FindField(updateField)).ToString(),out jzdj))
                    {
                        this.BeginInvoke(new MethodInvoker(() =>
                        {
                            try
                            {
                                MessageBox.Show("错误：宗地["+pFeature.OID+"]基准价格未计算。");
                                this.sBtnUpdate.Enabled = true;
                                this.sBtnUpdate.Text = "更新";
                                progressBarControl.Reset();
                                progressBarControl.EditValue = 0;
                                progressBarControl.Visible = false;
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }));
                        return;
                    }
                    double xjzdj = jzdj * (1.0 + double.Parse(qsdl) * mouths);
                    pFeature.set_Value(pFeature.Fields.FindField("XJZDJ"), xjzdj);
                    pFeature.set_Value(pFeature.Fields.FindField("GXSJ"), updateTime);
                    pFeature.Store();
                    pFeature = pFeatureCursor.NextFeature();
                }
                #endregion
                #region 结束编辑
                pWorkspaceEdit.StopEditOperation();
                if (pWorkspaceEdit.IsBeingEdited())
                {
                    pWorkspaceEdit.StopEditing(true);
                    this.BeginInvoke(new MethodInvoker(() =>
                    {
                        try
                        {
                            MessageBox.Show("更新完成！");
                            this.sBtnUpdate.Enabled = true;
                            this.sBtnUpdate.Text = "完成";
                            progressBarControl.Reset();
                            progressBarControl.EditValue = 0;
                            progressBarControl.Visible = false;
                            isRunning = false;
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }));
                }
                #endregion
            }
            catch (Exception ex)
            {
                this.BeginInvoke(new MethodInvoker(() =>
                {
                    try
                    {
                        MessageBox.Show("更新发生异常。" + ex.Message);
                        this.sBtnUpdate.Enabled = true;
                        this.sBtnUpdate.Text = "更新";
                        progressBarControl.Reset();
                        progressBarControl.EditValue = 0;
                        progressBarControl.Visible = false ;

                    }
                    catch (Exception son_ex)
                    {
                        throw son_ex;
                    }
                }));
                COM.LIB.LOG.LogOperator.WriteLog(ex.Message);
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pWorkspaceEdit);
                isRunning = false;
            }
        }

        private void DJUpdate_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (isRunning == true)
                {
                    //DialogResult dr = MessageBox.Show(this, "正在进行更新，您确定要退出吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    //if (dr == DialogResult.Yes)
                    //{
                    //    e.Cancel = false;
                    //}
                    //else
                    //{
                    //    updateThread.Abort();
                    //    e.Cancel = true;
                    //}
                    MessageBox.Show("正在进行更新，暂时不能退出！", "提醒");
                    e.Cancel = true;
                }
            }
            catch (Exception ex)
            {
                COM.LIB.LOG.LogOperator.WriteLog(ex.Message);
            }
        }
    }
}